package ee.android.kinokavad.fragments;

import java.util.ArrayList;
import java.util.List;

import org.joda.time.DateTime;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;

import ee.android.kinokavad.App;
import ee.android.kinokavad.R;
import ee.android.kinokavad.activities.KinoKavadActivity;
import ee.android.kinokavad.adapters.SessionAdapter;
import ee.android.kinokavad.data.Session;

public class SessionsFragment extends SherlockFragment implements OnItemClickListener, OnClickListener {

	private static final String TAG = SessionsFragment.class.getSimpleName();
	private static final int MENU_SHOW_SELECTED = 0;
	private static final int MENU_SHOW_ALL = 1;
	private long cinemaId;
	private DateTime mDateTime;
	private App kinokavad;
	private ArrayAdapter<Session> mAdapter;
	private boolean isAlive;

	public static Fragment newInstance(Bundle args) {
		Fragment f = new SessionsFragment();
		f.setArguments(args);
		return f;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		isAlive = false;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		isAlive = true;
		return inflater.inflate(R.layout.sessions_fragment, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		View footer = LayoutInflater.from(getActivity()).inflate(R.layout.sessions_footer, null);
		ListView list = (ListView) view.findViewById(R.id.sessionsList);
		View emptyView = getView().findViewById(R.id.emptyView);
		list.setEmptyView(emptyView);
		emptyView.setOnClickListener(this);
		list.setOnItemClickListener(this);
		list.addFooterView(footer, null, false);
		mAdapter = new SessionAdapter(getActivity(), new ArrayList<Session>());
		list.setAdapter(mAdapter);
		registerForContextMenu(list);
		loadSessions(mDateTime);

	}

	public void loadSessions(DateTime dateTime) {
		if (isAlive) {
			mDateTime = dateTime;
			if (mAdapter != null) {
				mAdapter.clear();
				List<Session> sessions = kinokavad.getDataController().loadSessionsForCinemaAndDate(cinemaId, mDateTime);
				int position = 0;
				for (Session session : sessions) {
					mAdapter.add(session);
					if (new DateTime(session.getDateTime()).isBeforeNow()) {
						position++;
						session.setBeforeNow(true);
					}
				}
				mAdapter.notifyDataSetChanged();
				if (position != 0) {
					((ListView) getView().findViewById(R.id.sessionsList)).setSelection(position);
				}
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle extras = getArguments();
		cinemaId = extras.getLong("cinemaId",0);
		mDateTime = new DateTime(extras.getString("date"));
		kinokavad = (App) getActivity().getApplicationContext();
		kinokavad.getDataController().open();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		kinokavad.getDataController().closeRequest();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int id, long position) {
		Session session = mAdapter.getItem((int) position);
		MainFragmentKinoKavad main = (MainFragmentKinoKavad) getActivity().getSupportFragmentManager()
				.findFragmentByTag(MainFragmentKinoKavad.class.getSimpleName());
		if (main != null)
			main.onMovieClicked(session.getMovieId());
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		if (v.getId()==R.id.sessionsList) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			Session session = mAdapter.getItem(info.position);
			menu.setHeaderTitle(session.getMovieTitle());
			menu.add((int) cinemaId, MENU_SHOW_ALL, 0, "Näita kõiki seansse");
			menu.add((int) cinemaId, MENU_SHOW_SELECTED, 1, "Näita valitud kinode seansse");
		}

	}

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {

		// In multi fragment layout, onContextItemSelected is called on all child fragments
		// Need unique identifier for each fragment, in this case cinemaId
		if (item.getGroupId() == cinemaId && 
				(item.getItemId() == MENU_SHOW_SELECTED || item.getItemId() == MENU_SHOW_ALL)) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
			Session session = mAdapter.getItem(info.position);
			KinoKavadActivity.replaceFragment(getActivity(), MovieSessionFragment.newInstance(session.getMovieId(), item.getItemId() == MENU_SHOW_SELECTED), true, false);	
			return true;
		}

		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.emptyView:
			KinoKavadActivity.reload((KinoKavadActivity) getActivity());
			break;

		default:
			break;
		}		
	}

}
